package com.nciae.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.ParserConfig;
import com.nciae.po.Hoursemaster;
import com.nciae.po.StudentUnion;
import com.nciae.dao.StudentUnionMapper;
import com.nciae.po.User;
import com.nciae.service.IStudentUnionService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nciae.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Guoliyu
 * @since 2022-03-31
 */
@Service
public class StudentUnionServiceImpl extends ServiceImpl<StudentUnionMapper, StudentUnion> implements IStudentUnionService {

    @Autowired
    private IUserService userService;

    @Override
    public List<StudentUnion> findAll(String username) {
        List<StudentUnion> studentUnions = new ArrayList<>();
        List<User> users = userService.findUserByUsername(username);
        for(User user:users) {
            StudentUnion studentUnion = baseMapper.selectById(user.getId());
            if (!Objects.isNull(studentUnion)) {
                studentUnion.setUser(user);
                studentUnions.add(studentUnion);
            }
        }
        return studentUnions;
    }

    @Override
    public void add(StudentUnion studentUnion) {
        ParserConfig.getGlobalInstance().addAccept("com.nciae.po.User");
        User user = (User) JSONObject.parse(studentUnion.getUserJson());
          if (!Objects.isNull(user)) {
              userService.add(user);
          }
      studentUnion.setId(user.getId());
      baseMapper.insert(studentUnion);
    }

    @Override
    public void update(StudentUnion studentUnion) {
        User user = (User) JSONObject.parse(studentUnion.getUserJson());
        if (!Objects.isNull(user)) {
            user.setId(studentUnion.getId());
            userService.update(user);
        }
        studentUnion.setId(user.getId());
        baseMapper.updateById(studentUnion);
    }

    @Override
    public void delete(Long id) {
        userService.delete(id);
        baseMapper.deleteById(id);
    }

    @Override
    public StudentUnion findStudentUnionById(Long id) {
        return baseMapper.selectById(id);
    }
}
